package com.pianzhu.blockchainemr.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.pianzhu.blockchainemr.mapper.DoctorMapper;
import com.pianzhu.blockchainemr.pojo.*;
import com.pianzhu.blockchainemr.pojo.Param.ChangeVisitStatusParam;
import com.pianzhu.blockchainemr.pojo.Param.EmpowerParam;
import com.pianzhu.blockchainemr.pojo.result.*;
import com.pianzhu.blockchainemr.service.DoctorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.Period;
import java.util.List;

@Service
public class DoctorServiceImpl implements DoctorService {

    @Autowired
    private DoctorMapper doctorMapper;

    @Override
    public PageResult<PatientResult> getMyPatients(
            Long doctorId, Integer pageNum, Integer pageSize,
            String patientName, String visitId) {

        // 1. 开始分页
        PageHelper.startPage(pageNum, pageSize);

        // 2. 查询数据
        List<PatientResult> patientResults = doctorMapper.getMyPatients(
                doctorId, patientName, visitId
        );
         // 设置年龄
        for (PatientResult patientResult : patientResults) {
            patientResult.setPatientAged(doctorMapper.getPatientAged(patientResult.getPatientId()));
        }

        // 3. 设置授权状态
        for (PatientResult patientResult : patientResults) {
            EmrDocumentsEmpower empower = doctorMapper.getEmpowerByVisitIdAndDoctorId(patientResult.getVisitId(), doctorId);
            patientResult.setIsEmpower(getEmpowerStatus(empower));
        }

        // 4. 获取分页信息
        PageInfo<PatientResult> pageInfo = new PageInfo<>(patientResults);

        // 5. 构建分页结果
        return new PageResult<>(
                pageInfo.getPageNum(),
                pageInfo.getPageSize(),
                pageInfo.getTotal(),
                pageInfo.getList()
        );
    }

    @Override
    public Long getMyPatientsCount(Long doctorId) {
        return doctorMapper.getMyPatientsCount(doctorId);
    }

    @Override
    public void changeVisitStatus(ChangeVisitStatusParam param) {
        // 添加参数验证
        if (param == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        String changeFunction = param.getChangeFunction();
        if (changeFunction == null || changeFunction.trim().isEmpty()) {
            throw new IllegalArgumentException("changeFunction 不能为空");
        }
        switch (changeFunction) {
            case "就诊中":
                doctorMapper.inVisit(param.getVisitId());
                break;
            case "出院":
                doctorMapper.discharge(param.getVisitId());
                break;
            case "转院":
                doctorMapper.transfer(param.getVisitId(), param.getHospitalId());
                break;
            case  "取消":
                doctorMapper.cancel(param.getVisitId());
                break;
            case "死亡":
                doctorMapper.dead(param.getVisitId());
        }
    }
    @Override
    @Transactional
    public List<MedicalRecordListResult> getMedicalRecord(String visitId, Integer doctorId) {
        List<MedicalRecordListResult> resultList = doctorMapper.getMedicalRecord(visitId);
        for (MedicalRecordListResult medicalRecordListResult : resultList) {
            switch (medicalRecordListResult.getDocType()){
                case "01":
                    medicalRecordListResult.setDocType("入院记录");
                    break;
                case "02":
                    medicalRecordListResult.setDocType("病程记录");
                    break;
                case "03":
                    medicalRecordListResult.setDocType("出院小结");
                    break;
                case "04":
                    medicalRecordListResult.setDocType("门诊病历");
                    break;
                default:
                    medicalRecordListResult.setDocType("其他");
            }
            String isEmpower = doctorMapper.isEmpower(doctorId, medicalRecordListResult.getDocId());
            switch (isEmpower) {
                case "0":
                    medicalRecordListResult.setIsEmpower("授权中");
                    break;
                case "1":
                    medicalRecordListResult.setIsEmpower("已授权");
                    break;
                case "2":
                    medicalRecordListResult.setIsEmpower("已拒绝");
                    break;
                case null:
                    medicalRecordListResult.setIsEmpower("未授权");
                    break;
                default:
                    medicalRecordListResult.setIsEmpower("未知");
            }
            MedicalRecordInfo medicalRecordInfo = new MedicalRecordInfo();
            if (medicalRecordListResult.getIsEmpower().equals("已授权")) {
                medicalRecordInfo = doctorMapper.getMedicalRecordInfo(medicalRecordListResult.getDocId());
                medicalRecordInfo.setPatientName(doctorMapper.selectRealNameByPatientId(medicalRecordInfo.getPatientId()));
                medicalRecordInfo.setDoctorName(doctorMapper.selectRealNameById(medicalRecordInfo.getDoctorId()));
                medicalRecordInfo.setDeptName(doctorMapper.selectDeptNameByDeptCode(medicalRecordInfo.getDeptCode()));
            }
            medicalRecordListResult.setMedicalRecordInfo(medicalRecordInfo);
        }
        return resultList;
    }

    @Override
    public void requestEmpower(EmpowerParam empowerParam) {
        doctorMapper.requestEmpower(empowerParam.getVisitId(), empowerParam.getDoctorId(), empowerParam.getDocId());
    }

    @Override
    public String getChiefComplaint(String visitId) {
        return doctorMapper.getChiefComplaint(visitId);
    }

    @Override
    @Transactional
    public List<MedicalReportListResult> getMedicalReport(String visitId, Integer doctorId) {
        List<MedicalReportListResult> resultList = doctorMapper.getMedicalReport(visitId);
        for (MedicalReportListResult medicalReportListResult : resultList) {
            String isEmpower = doctorMapper.isReportEmpower(doctorId, medicalReportListResult.getReportId());
            switch (isEmpower) {
                case "0":
                    medicalReportListResult.setIsEmpower("授权中");
                    break;
                case "1":
                    medicalReportListResult.setIsEmpower("已授权");
                    break;
                case "2":
                    medicalReportListResult.setIsEmpower("已拒绝");
                    break;
                case null:
                    medicalReportListResult.setIsEmpower("未授权");
                    break;
                default:
                    medicalReportListResult.setIsEmpower("未知");
            }
            MedicalReportInfo medicalReportInfo = new MedicalReportInfo();
            if (medicalReportListResult.getIsEmpower().equals("已授权"))
            {
                medicalReportInfo = doctorMapper.getMedicalReportInfo(medicalReportListResult.getReportId());
                String doctorName = doctorMapper.selectRealNameById(medicalReportInfo.getVerifyDoctorId());
                String reporterName = doctorMapper.selectRealNameById(medicalReportInfo.getReporterId());
                medicalReportInfo.setVerifyDoctorName(doctorName);
                medicalReportInfo.setReporterName(reporterName);

            }
            medicalReportListResult.setMedicalReportInfo(medicalReportInfo);
        }
        return resultList;
    }

    @Override
    public void requestMedicalReportEmpower(EmpowerParam empowerParam) {
        doctorMapper.requestMedicalReportEmpower(empowerParam.getVisitId(), empowerParam.getDoctorId(), empowerParam.getReportId());
    }

    @Override
    public List<PatientResult> searchPatients(Long doctorId, String keyword) {
        List<PatientResult> patientResults = doctorMapper.searchPatients(doctorId, keyword);
        for (PatientResult patientResult : patientResults) {
            patientResult.setPatientAged(doctorMapper.getPatientAged(patientResult.getPatientId()));
            patientResult.setHospitalName(doctorMapper.getHospitalName(patientResult.getHospitalId()));
            patientResult.setDeptName(doctorMapper.selectDeptNameByDeptCode(patientResult.getDeptCode()));
        }

        return patientResults;
    }

    @Override
    @Transactional
    public void newMedicalRecord(EmrDocuments emrDocuments) {
        doctorMapper.newMedicalRecord(emrDocuments);
        emrDocuments.setDocId(doctorMapper.getDocIdByVisitIdAndTitle(emrDocuments.getVisitId(), emrDocuments.getDocTitle()));
        doctorMapper.requestEmpower(emrDocuments.getVisitId(), emrDocuments.getWriterDoctorId(), emrDocuments.getDocId());
        doctorMapper.updateEmpowerStatus(emrDocuments.getDocId(), emrDocuments.getWriterDoctorId(),"1");
    }

    @Override
    public void newMedicalReport(EmrExamReports emrExamReports) {
        doctorMapper.newMedicalReport(emrExamReports);
    }

    @Override
    public List<EmrExamItemDict> getItemList() {
        return doctorMapper.getItemList();
    }

    @Override
    @Transactional
    public List<EmrMedOrders> getPrescriptionList(String patientId) {
        List<EmrMedOrders> emrMedOrdersList = doctorMapper.getPrescriptionList(patientId);
        for (EmrMedOrders emrMedOrders : emrMedOrdersList) {
            emrMedOrders.setDoctorName(doctorMapper.selectRealNameById(emrMedOrders.getOrderingDoctorId()));
        }
        return emrMedOrdersList;
    }

    @Override
    public void createPrescription(EmrMedOrders emrMedOrders) {
        doctorMapper.createPrescription(emrMedOrders);
    }

    @Override
    public EmrPatMaster getPatientInfo(String patientId) {
        EmrPatMaster emrPatMaster = doctorMapper.getPatientInfo(patientId);
        LocalDate currentDate = LocalDate.now();
        LocalDate birthDate = emrPatMaster.getBirthDate().toLocalDate();
        Integer age = Period.between(birthDate, currentDate).getYears();
        emrPatMaster.setAge(age);
        return emrPatMaster;
    }

    @Override
    public List<EmrDrugDict> getDrugList() {
        return doctorMapper.getDrugList();
    }

    @Override
    public List<EmrMedVisit> getVisitList(String patientId, Integer doctorId) {
        List<EmrMedVisit> emrMedVisitList = doctorMapper.getVisitList(patientId,doctorId);
        return emrMedVisitList;
    }

    @Override
    public List<EmrMedOrders> getMyPrescriptionList(String doctorId) {
        List<EmrMedOrders> emrMedOrdersList = doctorMapper.getMyPrescriptionList(doctorId);
        return emrMedOrdersList;
    }

    @Override
    public void deletePrescription(EmrMedOrders emrMedOrders) {
        doctorMapper.deletePrescription(emrMedOrders.getOrderId());
    }

    @Override
    public void updatePrescription(EmrMedOrders emrMedOrders) {
        doctorMapper.updatePrescription(emrMedOrders);
    }

    /**
     * 根据授权信息获取授权状态
     */
    private String getEmpowerStatus(EmrDocumentsEmpower empower) {
        if (empower == null) {
            return "未授权";
        }
        switch (empower.getIsEmpower()) {
            case "0":
                return "授权中";
            case "1":
                return "已授权";
            case "2":
                return "已拒绝";
            default:
                return "未知";
        }
    }
}